package com.yangy.flvdemo.controller;

import com.yangy.flvdemo.dto.Data;
import com.yangy.flvdemo.ffmpeg.RTSPToFLVStreamer;
import com.yangy.flvdemo.ffmpeg.VideoStreamerBucket;
import org.springframework.web.bind.annotation.*;

/**
 * @author YangYuan
 * @date 2024/7/3
 */
@RestController
@RequestMapping("/video")
public class FlvController {

    //windows 系统下未配置环境变量，可写具体路径
//    String ffmpge = "D:\\soft\\ffmpeg-2024-05-13-git-37db0454e4-full_build\\bin\\ffmpeg.exe";
    String ffmpge = "ffmpeg";

    /**
     * 演示示例接口，不适用于生产环境
     * @param code 可以是视频编码，任意唯一字符串
     * @param rtsp 任意rtsp流地址
     * @return
     * @throws InterruptedException
     */
    @PostMapping("/play")
    public String getPlayUrlV2(@RequestBody Data data){

        String playUrl = "http://10.0.0.110:80/live?port=1935&app=mlive&stream="+data.getCode();
        //已开启流推送，直接返回
        if (VideoStreamerBucket.isActive(data.getCode())){
            return playUrl;
        }

        String ffmpegCommand = ffmpge+" -rtsp_transport tcp -i \""+data.getRtsp()+"\" -f flv -vcodec libx264 -vprofile baseline -acodec aac -tune zerolatency -preset ultrafast -ar 44100 -strict -2 -ac 1 -s 1980x1080 -q 1 \"rtmp://10.0.0.110:1935/mlive/"+data.getCode()+"\"";

        VideoThread videoThread = new VideoThread(ffmpegCommand, data.getCode());
        videoThread.start();

        return playUrl;
    }



    private class VideoThread extends Thread{

        private String ffmpegCommand;
        private String code;

        public VideoThread(String ffmpegCommand, String code) {
            this.ffmpegCommand = ffmpegCommand;
            this.code = code;
        }

        @Override
        public void run() {
            RTSPToFLVStreamer flvStreamer = new RTSPToFLVStreamer(ffmpegCommand);
            flvStreamer.startStreaming(code);
        }


    }
}
